﻿using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppNetworkTestAndToEmail
{
    /// <summary>
    /// 邮件服务器类型
    /// </summary>
    internal enum ServerType
    {
        /// <summary>
        /// 163邮件服务器
        /// </summary>
        SERVER_163_COM,

        /// <summary>
        /// qq邮件服务器
        /// </summary>
        SERVER_qq_COM,
    }

    /// <summary>
    /// 发送邮件处理类
    /// </summary>
    internal class SendEmailTool
    {

        /// <summary>
        /// 文件
        /// </summary>
        const string path = "";

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mailFrom">发件人</param>
        /// <param name="mailTo">收件人</param>
        /// <param name="title">标题</param>
        /// <param name="content">发送内容</param>
        /// <param name="mailFromAccount">发件人账号</param>
        /// <param name="mailPassword">收件人邮箱授权码</param>
        /// <param name="serverType">服务器类型；</param>
        internal static void TestSmtpClient(string mailFrom, string mailTo, string title, string content, string mailFromAccount, string mailPassword, ServerType serverType)
        {
            MailMessage mymail = new MailMessage();
            mymail.From = new System.Net.Mail.MailAddress(mailFrom);
            mymail.To.Add(mailTo);
            mymail.Subject = title;
            mymail.Body = content;
            mymail.IsBodyHtml = true;
            //mymail.Attachments.Add(new Attachment(path));

            System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();

            smtpclient.Timeout = 8000;//毫秒
            smtpclient.UseDefaultCredentials = false;
            smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;

            if (serverType == ServerType.SERVER_163_COM)
            {
                smtpclient.Port = 25;
                smtpclient.Host = "smtp.163.com";
            }
            else
            {
                //smtpclient.Port = 465;
                smtpclient.Port = 587;
                smtpclient.Host = "smtp.qq.com";
            }

            smtpclient.EnableSsl = true;
            smtpclient.Credentials = new System.Net.NetworkCredential(mailFromAccount, mailPassword);
            try
            {
                smtpclient.Send(mymail);
                LogHelpter.AddLog($"发送成功，接收人{mailTo},标题={title}，内容={content}");
            }
            catch (Exception ex)
            {
                LogHelpter.AddLog($"发送邮件失败.请检查.接收人{mailTo},标题={title}，内容={content}" + ex.Message, null, "emailError");
            }
        }
    }
}
